package com.kmdd.xtds.ui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.kmdd.xtds.configs.BloodRecord
import com.kmdd.xtds.configs.PrefsManager
import com.kmdd.xtds.databinding.ActivityBloodRecordAddBinding
import com.kmdd.xtds.room.BloodPressureDatabase
import com.kmdd.xtds.toast
import com.kmdd.xtds.util.emptyReplaceDefault
import com.kmdd.xtds.util.launch
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.withContext

class BloodRecordAddActivity : AppCompatActivity() {

    private lateinit var binding: ActivityBloodRecordAddBinding

    companion object {

        fun start(context: Context) {
            context.startActivity(Intent(context, BloodRecordAddActivity::class.java))
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityBloodRecordAddBinding.inflate(layoutInflater)
        setContentView(binding.root)
        immersionBar {
            transparentBar()
            keyboardEnable(true)
            fitsSystemWindows(false)
            statusBarDarkFont(false)
        }


        launch {
            PrefsManager.bloodRecordFlow.collectLatest {
                binding.etBlood.setText(it.bloodValue)
                binding.etHeight.setText(it.bloodHeight)
                binding.tvWeight.setText(it.bloodWeight)
            }
        }

        binding.frameLayoutBack.setOnClickListener {
            finish()
        }

        binding.tvSave.setOnClickListener {

            val bloodValue = binding.etBlood.text.trim().toString()

            val heightValue = binding.etHeight.text.trim().toString()

            val weightValue = binding.tvWeight.text.trim().toString()

            if (TextUtils.isEmpty(bloodValue)) {
                toast("请输入血糖值")
                return@setOnClickListener
            }

            val bloodRecord = BloodRecord(
                bloodValue,
                heightValue.emptyReplaceDefault("0"),
                weightValue.emptyReplaceDefault("0")
            )

            PrefsManager.bloodValue = bloodRecord


            //保存数据库
            launch(onError = {
                //保存失败
                toast("保存失败")
            }) {
                withContext(Dispatchers.IO) {
                    BloodPressureDatabase.getInstance(this@BloodRecordAddActivity)?.bloodSugarDao()
                        ?.insert(listOf(bloodRecord.toDataBase()))
                }
            }
            toast("保存成功")
            finish()
        }
    }
}